<?php

namespace App\Console\Commands\Invoice;

use App\Models\Invoice\InvoiceHistoryModel;
use App\Remote\Orm\InvoiceRemote;
use App\Service\Invoice\InvoiceService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Validation\ValidationException;

class ResetInvoiceBaseInfoCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'invoice:resetInvoiceBaseInfo {id}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '重置待开票基础数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     * @throws ValidationException
     */
    public function handle(): int
    {
        $invoiceId = $this->input->getArgument("id");

        // todo 查询基础数据
        $invoiceModel = InvoiceHistoryModel::query()
                                           ->with("businessRel")
                                           ->where("id", $invoiceId)
                                           ->whereIn("status",
                                               [InvoiceHistoryModel::STATUS_1, InvoiceHistoryModel::STATUS_2])
                                           ->first();

        if (!$invoiceModel) {
            $this->error("指定开票记录不存在，或当前记录状态不支持修改基础数据,请核实后重试");
            return 0;
        }

        //todo 获取orm订单数据
        $detailsCollect = collect(InvoiceRemote::previewInvoice(
            $invoiceModel->businessRel->pluck("businessId")->toArray()
        )["lists"]);

        // todo 更新原始数据
        InvoiceHistoryModel::query()
                           ->where("id", $invoiceId)
                           ->update([
                               "status"                => InvoiceHistoryModel::STATUS_1,
                               "errorMsg"              => "",
                               "invoiceTotalAmount"    => (string)$detailsCollect->pluck("total_price")->sum(),
                               "invoiceTaxTotalAmount" => (string)$detailsCollect->pluck("tax_price")->sum(),
                               "businessDetails"       => $detailsCollect->toJson(JSON_UNESCAPED_UNICODE),
                               "updatedAt"             => time(),
                               "updatedByUid"          => 0
                           ]);

        // ToDo 同步orm开票状态
        InvoiceService::syncOrmOrderInvoiceStatus($invoiceId, InvoiceHistoryModel::STATUS_1);

        return 0;
    }
}
